
<template>
    <main :style="{ backgroundImage: `url(${url})` }">
        <template v-if="current">
            <div class="header">
                <div class="left">
                    <img alt="" class="back" :src="url1" @click="back" />
                    <span>{{ name }}</span>
                </div>
                <div class="right">
                    <Progress class="progress" :max="list.length" :value="currentIndex + 1" :progressColor="progressColor()"></Progress>
                    <!-- <div class="progress-wrap">
                        <progress :class="[`progress-${path}`]" :max="list.length" :value="value"></progress>
                        <span>{{ `${value}/${list.length}` }}</span>
                    </div> -->
                </div>
            </div>
            <div class="article">
                <!-- :class="{ 'li-focus': currentIndex == i }"> -->
                <ul ref="ulRef">
                    <li v-for="(item, i) in list" :key="i" :tabindex="currentIndex === i ? '0' : ''"
                        ref="liRef" @click="click(item, i)"
                        :style="{ borderColor: liFoucusColor(i) }">
                        <div class="cell-group">
                            <div class="cell-icon">
                                <img :src="urlCPlay" alt="">
                            </div>
                            <div class="cell-text">
                                <div class="en" v-html="item.content"></div>
                                <div class="cn" v-html="item.translation"></div>
                            </div>
                        </div>
                        <div class="cell-score-wrap" v-show="item.read">
                            <div class="scores">
                                <!-- <img alt="" src="../public/assets/diandu_tb_8_pt.svg" /> -->
                                <span>{{ item.total }}</span>
                            </div>
                            <span>流畅度：{{ item.fluency }}分</span>&nbsp;
                            <span>完整度：{{ item.integrity }}分</span>&nbsp;
                            <span>准确度：{{ item.accuracy }}分</span>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="footer" @click.prevent="functionEvent">
                <div class="footer-wrap">
                    <div @click.prevent="my"
                        class="footer-btn-wrap footer-btn-left-wrap">
                        <div class="footer-btn">
                            <template v-if="current.isCanPlay">
                                <template v-if="current.isPlay">
                                    <img :src="urlPause" alt=""
                                    style="width: 100%; height: 100%" />
                                </template>
                                <template v-else>
                                    <img :src="urlPlay" alt=""
                                    style="width: 100%; height: 100%" />
                                </template>
                            </template>
                            <template v-else>
                                <img :src="urlPlayGray" alt=""
                                style="width: 100%; height: 100%" />
                            </template>
                        </div>
                        <span class="footer-btn-title">我的录音</span>
                    </div>
                    <template v-if="value !== list.length">
                        <div 
                            v-show="!recordingOpen"
                            :style="{ color: '#333' }" 
                            class="footer-btn-wrap footer-btn-middle-wrap"
                            @click.prevent="read">
                            <div class="footer-btn footer-btn-middle reading">
                                <img alt="" :src="urlRecord" style="width: 100%; height: 100%" />
                            </div>
                            <span class="footer-btn-title">{{ current.read ? "再读一次" : "跟读测评" }}</span>
                        </div>
                    </template>
                    <template v-else>
                        <div class="footer-btn-wrap footer-btn-middle-wrap" @click.prevent="refresh">
                            <div class="footer-btn footer-btn-middle reading">
                                <img alt="" :src="urlRefresh" style="width: 100%; height: 100%" />
                            </div>
                            <span class="footer-btn-title">重新测评</span>
                        </div>
                    </template>

                    <div @click.prevent="next"
                        class="footer-btn-wrap  footer-btn-right-wrap">
                        <div class="footer-btn">
                            <template v-if="currentIndex == list.length - 1">
                                <img alt="" :src="urlNextGray"
                                style="width: 100%; height: 100%" />
                            </template>
                            <template v-else>
                                <img alt="" :src="urlNext"
                                style="width: 100%; height: 100%" />
                            </template>
                        </div>
                        <span class="footer-btn-title">下一句</span>
                    </div>
                </div>
            </div>
        </template>
    </main>
    <Dialog :open="recordingOpen">
        <img alt="" class="recording" src="../public/assets/expression/ty_tb_3_pt@2x.png" />
        <div class="animation footer-btn-wrap footer-btn-record-middle-wrap"
            :style="{ color: 'white' }" 
            @click.prevent="read">
            <div class="footer-btn footer-btn-middle reading">
                <img alt="" :src="urlRecord" style="width: 100%; height: 100%" />
            </div>
            <span class="footer-btn-title">点击停止</span>
        </div>
    </Dialog>
    <Dialog :open="audioAuth">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioAuth = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-auth" src="../public/assets/expression/diandu_tb_16_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    请打开麦克风访问权限
                </div>
            </div>                
        </div>
    </Dialog>
    <Dialog :open="audioNoDevice">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioNoDevice = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-device" src="../public/assets/expression/diandu_tb_17_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    很抱歉，监测到您的设备没有麦克风
                </div>
            </div>                
        </div>
    </Dialog>
    <Dialog :open="audioNoNet">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioNoNet = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-net" src="../public/assets/expression/diandu_tb_15_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    网络不佳，请稍等片刻
                </div>
            </div>                
        </div>
    </Dialog>
    <Dialog :open="confirmOpen">
        <div class="dialog-wrap-confirm">
            <div class="confirm-content">
                <img alt="" :src="urlDlog" />
                <span>你还没有完成评测，确定要退出吗？</span>
                <div class="control">
                    <button @click="confirmBtn" class="button btn-back"
                    :style="{ background: buttonBackColor() }"
                    >退出</button>
                    <button @click="confirmOpen = false" class="button btn-agin"
                        :style="{ background: buttonAginColor() }">取消</button>
                </div>
            </div>
        </div>
    </Dialog>
</template>

<script setup>
import { onMounted, ref, reactive, toRefs, watch, onUnmounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import AudioWebsocket from './../utils/audio.js'
import Dialog from "../component/dialog/index.vue";
import { getSentenceDetailApi } from "../api/expression.js"
import '../css/evaluation.css'
import Progress from "../component/progress/index.vue";

const router = useRouter();
const route = useRoute();
const { id, name } = route.query;

const path = window.gradeId > 61 ? 'middle' : 'primary';

const url =  new URL(`../public/assets/expression/${path}/d_bg.png`, import.meta.url).href;
const url1 = new URL(`../public/assets/book/${path}/back.png`, import.meta.url).href;
const url2 = new URL(`../public/assets/expression/${path}/poprightclose.png`, import.meta.url).href;

const urlNext = new URL(`../public/assets/expression/${path}/next.png`, import.meta.url).href;
const urlNextGray = new URL(`../public/assets/expression/${path}/next_gray.png`, import.meta.url).href;
const urlRecord = new URL(`../public/assets/expression/${path}/record.png`, import.meta.url).href;
const urlPre = new URL(`../public/assets/expression/${path}/pre.png`, import.meta.url).href;
const urlPreGray = new URL(`../public/assets/expression/${path}/pre_gray.png`, import.meta.url).href;
const urlCPlay = new URL(`../public/assets/expression/${path}/c_play.png`, import.meta.url).href;
const urlRefresh = new URL(`../public/assets/expression/${path}/refresh.png`, import.meta.url).href;
const urlPlay= new URL(`../public/assets/expression/${path}/play.png`, import.meta.url).href;
const urlPlayGray = new URL(`../public/assets/expression/${path}/play_gray.png`, import.meta.url).href;
const urlPause= new URL(`../public/assets/expression/${path}/pause.png`, import.meta.url).href;

const urlDlog= new URL(`../public/assets/expression/${path}/dlog_img.png`, import.meta.url).href;

const state = reactive({
    list: [],
    current: null,
    currentIndex: 0
});

const liRef = ref();
const ulRef = ref();

const { list, current, currentIndex } = toRefs(state);

// state.list = expDetail[id].map(i => {
//     i.read = false;
//     i.isPlay = false;
//     return i;
// })
// state.current = state.list[0];

const value = ref(0);

const readBtnTitle = ref("跟读测评");
const confirmOpen = ref(false);
const recordingOpen = ref();
const catalogOpen = ref(false);
const audioAuth = ref(false);
const audioNoDevice = ref(false);
const audioNoNet = ref(false);

const audio = new Audio();
audio.onended = () => {
    //   console.log("要结束了");
    state.current.isPlay = false;
};
const audioUrl = ref('')

const getSentenceDetail = async (id) => {
    // state.list = expDetail[id].map(i => {
    //     i.read = false;
    //     i.isPlay = false;
    //     return i;
    // })
    // state.current = state.list[0];
    // audioPlay();

    try {
        const res = await getSentenceDetailApi(id);
        // console.log('res', res);
        if (res.data && res.data.length) {
            state.list = res.data.map(i => {
                i.read = false;
                i.isPlay = false;
                i.isCanPlay = false;
                return i;
            })
            state.current = state.list[0];
            audioPlay();
        }

    } catch (error) {
        // console.log(error);
    }
}

const audioPlay = (url) => {
    if (!audio.paused) {
        audio.pause();
    }
    let audio_src = url || state.list[state.currentIndex].audio_url;
    audio.src = audio_src;

    // audio.src = 'assets/GradeFiveDown/5109/79_u1exp1.mp3';

    // console.log('import.meta.url',import.meta.url);
    // audio.src =  new URL('assets/GradeFiveDown/5109/79_u1exp1.mp3', import.meta.url).href;
    // console.log('audio.src',audio.src);
    audio.play();
}

const audioStop = () => {
    audio.pause();
}

onMounted(() => {
    getSentenceDetail(id);
});

onUnmounted(() => {
    audioStop();
    // AudioWebsocket.pauseRecord();
    if (timer) {
        clearTimeout(timer);
    }
})

const back = () => {
    if (value.value === state.list.length) {
        router.go(-1)
    } else {
        confirmOpen.value = true;
    }
}

const refresh = () => {
    state.list.forEach((i) => {
        i.read = false;
        i.isPlay = false;
        i.isCanPlay = false;
    });
    value.value = 0;

    state.current = state.list[0];
    state.currentIndex = 0;

    ulRef.value && (ulRef.value.scrollTop = 0)

    audioPlay();
}

function my() {
    if (!state.current.isCanPlay) {
        return;
    }
    if (state.current.isPlay) {
        // AudioWebsocket.pauseRecord();
        audioStop();
        state.current.isPlay = false;
    } else {
        audioPlay(state.current.audioUrl);
        state.current.isPlay = true;
    }
}

let timer = null;
const timeout = () => {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        read();
    }, 20 * 1000);
}

let isClickRead = false;
function read() {
    if (isClickRead) return
    isClickRead = true;
    onRead();
    // setTimeout(() => {
    //     isClickRead = false
    // }, 1000)
}

// let content = "hello @#$$$h.e-l'lo;.!?";
// content = content.replace(/[^a-zA-Z\.\!\?\; ]/g, "");
// console.log('content',content);

// let content = "hello @#$$$h.e-l'lo;.!?";
// content = content.replace(/[^a-zA-Z\.\-\' ]/g, "");
// console.log('content',content);


const onRead = () => {
    console.log('23435');
    audioStop();
    state.current.isPlay = false;
    if (recordingOpen.value) {
        stopRead();
    } else {
        AudioWebsocket.hasAudioinput().then(() => {
            let content = state.current.content.replace(/<[^>]*>/g, '').replace(/[^a-zA-Z0-9\.\-\'\!\?\; ]/g, "");
            console.log('content',content);
            AudioWebsocket.startRecording(content, 'sentence', (result) => {
                // console.log('result', result);
                let coe = 20;
                state.current.fluency = parseInt(result.fluency * coe);
                state.current.integrity = parseInt(result.integrity * coe);
                state.current.accuracy = parseInt(result.accuracy * coe);
                state.current.total = parseInt(result.total * coe);

                state.current.read = true;
                value.value = state.list.filter(({ read }) => read).length;

                scrollToItem();

            }, (blob) => {
                // console.log('AudioWebsocket.startRecording', flag);
                state.current.isCanPlay = true;
                state.current.audioUrl = URL.createObjectURL(blob);
                // audioUrl.value = URL.createObjectURL(blob);
            }).then(() => {
                recordingOpen.value = true;
                readBtnTitle.value = "点击停止";
                timeout();
                isClickRead = false;
            }).catch(errorCode => {
                if (errorCode == 40001) {
                    // 无法获取麦克风权限
                    audioAuth.value = true;
                } else if ( errorCode == 40002 ) {
                    // 连接websocket失败
                    audioNoNet.value = true;
                    stopRead();
                }
                isClickRead = false;
            });
        }).catch(error => {
            // 未获取麦克风设备
            audioNoDevice.value = true;
            isClickRead = false;
        });
    }
}

const stopRead = () => {
    console.log('点击停止');
    recordingOpen.value = false;
    readBtnTitle.value = "跟读测评";
    AudioWebsocket.stopRecording();
    if (timer) {
        clearTimeout(timer);
    }
    isClickRead = false;
}

function next() {
    if (state.currentIndex >= state.list.length - 1) {
        return;
    }
    // state.current.isCanPlay = false;
    state.current.isPlay = false;

    state.currentIndex++;
    state.current = state.list[state.currentIndex];

    audioPlay();

    // let item = liRef.value[0].getBoundingClientRect();

    // let container = ulRef.value.getBoundingClientRect();

    // console.log('container',container, item);

    // ulRef.value && ulRef.value.scrollTo({
    //       top: 0,
    //       behavior: 'smooth'
    //     })

    scrollToItem();
    // liRef.value && liRef.value[0] && liRef.value[0].scrollIntoView({ behavior: "smooth" }); // smooth滚动效果
}
const scrollToItem = (index) => {
    nextTick(() => {
        console.log('ulRef.value && liRef.value',ulRef.value , liRef.value);
        if (ulRef.value && liRef.value) {
            const element = liRef.value[state.currentIndex];
            if (element) {
                // let itemRect = element.getBoundingClientRect();
                // let marginTop = window.getComputedStyle(element).marginTop;
                // console.log('marginTop',marginTop);

                // const scrollTop = element.offsetTop - ulRef.value.offsetTop - parseFloat(marginTop);
                
                // console.log('element.offsetTop',element.offsetTop);
                // console.log('ulRef.value.offsetTop',ulRef.value.offsetTop);

                let ulRect = ulRef.value.getBoundingClientRect();
                const rect = element.getBoundingClientRect();

                console.log('ulRect',ulRect);
                console.log('rect',rect);
                let isVisible = true;
                if (rect.bottom < 0 || rect.top > ulRect.height) {
                    isVisible = false;
                }

                console.log('isVisible',isVisible);
                // if (!isVisible) {
                //     const scrollTop = element.offsetTop - ulRef.value.offsetTop;
                //     ulRef.value.scrollTop = scrollTop;
                // }

                const scrollTop = element.offsetTop - ulRef.value.offsetTop;
                ulRef.value.scrollTop = scrollTop;

            }
        }
    });
}

function click(item, i) {
    // if (state.currentIndex != i) {
    //     state.current.isCanPlay = false;
    // }
    state.current.isPlay = false;

    state.current = item;
    state.currentIndex = i;
    audioPlay();

    scrollToItem();
    // liRef.value && liRef.value[0] && liRef.value[0].scrollIntoView({ behavior: "smooth" }); // smooth滚动效果
}
function functionEvent() {
    // activeElement.focus();
}
function confirmBtn() {
    confirmOpen.value = false;
    router.go(-1);

    // // console.log(confirmOpen.value);
    // if (confirmOpen.value === "back") {
    //     router.go(-1);
    // } else {
    //     catalogOpen.value = true;
    // }
}

const liFoucusColor = (i) => {
    if (state.currentIndex != i) {
        return 'transparent';
    }
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return '#0A91F1'
    }

    // switch (path) {
    //     case '51':
    //         return '#61BD66'
    //     case '81':
    //         return '#1E4BA6'
    //     default:
    //         return '#61BD66'
    // }
}

const buttonBackColor = () => {
    if (path == 'middle') {
        return '#FFA53E'
    } else {
        return 'linear-gradient(to bottom, #FFC55E, #ED9900)'
    }
}

const buttonAginColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return 'linear-gradient(to bottom, #85D389, #61BD66)'
    }
}

const progressColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return '#FFB530'
    }
}

</script>

<style scoped>

.article {
    /* height: 75%; */
    flex: 1;
    margin: 2% auto;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.article {
    overflow: hidden;
}

ul {
    height: 100%;
    overflow-y: scroll;
    padding-left: 1rem;
    width: 75%;
    margin: 2.3rem 0 2.3rem 0;
}

ul::-webkit-scrollbar {
    display: none;
}

ul::-webkit-scrollbar {
    width: 0px;
}

li {
    background-color: white;
    border: transparent solid 0.15rem;
    border-radius: 1rem;
    font-size: xx-large;
    list-style: none;
    margin: 0 1rem 1rem 1rem;
    position: relative;
    overflow: hidden;
    /* text-align: center; */
}

/* li:focus {
    border-color: #61bd66;
} */

.li-focus {
    border-color: #0A91F1;
}

/* li:focus::before {
    background-image: url("../public/assets/diandu_an_18_pt.svg");
    background-size: cover;
    content: "";
    cursor: pointer;
    display: block;
    height: 3rem;
    left: 0.5rem;
    position: absolute;
    top: 0.5rem;
    width: 3rem;
} */

li header {
    padding: 2% 0;
}

li footer {
    background-color: #fff4df;
    border-radius: 0 0 0.7rem 0.7rem;
    column-gap: 2rem;
    display: flex;
    font-size: x-large;
    justify-content: center;
    padding: 1% 0;
}

.cell-score-wrap {
    background-color: #FFF4DF;
    color: #D28700;
    text-align: center;
    font-size: 1.2rem;
    /* font-weight: bold; */
    position: relative;
    margin-top: 2rem;
    padding: 0.4rem 0;
}

.cell-score-wrap .scores {
    position: absolute;
    bottom: 0;
    left: 5%;
    width: 3rem;
    height: 3rem;
    background-image: url('../public/assets/expression/diandu_tb_8_pt.svg');
    background-size: cover;
    line-height: 3rem;
}

.cell-score-wrap  .scores span {
    color: #d28700;
    height: 3rem;
    left: 50%;
    position: absolute;
    top: 45%;
    transform: translate(-50%, -50%);
}

.cell-group {
    display: flex;
    padding: 1.4rem;
}

.cell-icon {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.cell-icon img {
    position: relative;
    margin-top: 0.1rem;
    width: 2rem;
}

.cell-text {
    margin-left: 1rem;
    flex: 1;
}

.en {
    font-size: 1.6rem;
    color: #222;
    font-family: 'text-en';
}

.cn {
    margin-top: 1.5rem;
    font-size: 1.4rem;
    color: #222;
}

</style>
